package com.hb.trade.server.project.section.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.core.pojo.enums.ProblemStatusEnum;
import com.hb.core.pojo.enums.SectionStatusEnum;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.section.dto.ProblemDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.core.pojo.project.section.entity.Problem;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import com.hb.trade.server.project.section.service.raw.ProblemService;
import com.hb.trade.server.project.util.DateUtil;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.ZoneId;

/**
 * <p>
 * 投标人/供应商提出问题表 前端控制器
 * </p>
 *
 * @author zhongdl
 * @since 2021-11-16
 */
@RestController
public class ProblemController {

   protected final ProblemService problemService;
   protected final BidSectionService bidSectionService;

    public ProblemController(ProblemService problemService,
                             BidSectionService bidSectionService) {
        this.problemService = problemService;
        this.bidSectionService = bidSectionService;
    }

    /**
     * 供应商提出问题
     *
     * @param problem
     * @return {@link jnpf.base.ActionResult}
     */
    @PostMapping("/problem/saveProblem")
    public Message saveProblem(@RequestBody ProblemDTO problem) {
        String msg = problem.paramsValid();
        if (StrUtil.isNotEmpty(msg)){
            return MsgUtil.fail(msg);
        }
        BidSection bidSection = bidSectionService.getById(problem.getSectionId());
        // 判断是否在答疑时间内
        if (bidSection.getClarificationSubmissionEndTime() != null && DateUtil.getMillis2()>bidSection.getClarificationSubmissionEndTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()){
            return MsgUtil.fail("答疑时间已截止！");
        }
        //设置必要字段 提出人id 供应商id等
        //problem.setRequiredFields(1);
        problem.setType(Integer.valueOf(1));
        problem.buildBaseData(1,problem.getProposerName(),problem.getProposerId());
        problemService.save(problem);
        return MsgUtil.success();
    }

    /**
     * 供应商提出问题列表(投标人用)
     *
     * @param problem
     * @return {@link jnpf.base.ActionResult}
     */
    @PostMapping("/problem/findProblemListBySectionId")
    public Message<PageResult<ProblemDTO>> findProblemListBySectionId(@RequestBody ProblemDTO problem) {
        Page<Problem> pages = problem.pages();
        QueryWrapper<Problem> problemQueryWrapper = new QueryWrapper<>();
        problemQueryWrapper.lambda().eq(Problem::getSectionId,problem.getSectionId())
                .eq(Problem::getType,Integer.valueOf(1))
//                .eq(Problem::getStatus,Integer.valueOf(2))
                .orderByDesc(Problem::getProposerTime);
        //分页查询当前标段和供应商的提出的问题
        problemService.page(pages, problemQueryWrapper);
        return MsgUtil.success(PageResult.get(pages).transferTo(ProblemDTO.class));
    }

    /**
     * 供应商发出问题
     *
     * @param id 提出问题id
     * @return {@link jnpf.base.ActionResult}
     */
    @PostMapping("/problem/sendOutProblem")
    public Message sendOutProblem(@RequestParam Long id) {
        Problem problem = problemService.getById(id);
        if (problem == null){
            return MsgUtil.success();
        }
        //只有待发出的状态下的问题才能发出
        if (ProblemStatusEnum.TO_BE_ISSUED.getCode() != problem.getStatus()){
           return MsgUtil.fail("只有待发出的问题才能发出");
        }
        problem.setStatus(ProblemStatusEnum.ISSUED.getCode());
        problemService.updateById(problem);
        return MsgUtil.success();
    }

    /**
     * 供应商提出问题列表(招标人用)
     *
     * @param problem
     * @return {@link Message}
     */
    @PostMapping("/problem/findBiddingProblemListBySectionId")
    public Message<PageResult<ProblemDTO>> findBiddingProblemListBySectionId(@RequestBody ProblemDTO problem) {
        //分页查询当前标段和供应商的提出的问题
        Page<ProblemDTO> pages = problemService.getProblemBySectionId(problem.pages(), problem.getSectionId(),problem.getProjectId());
        return MsgUtil.success(PageResult.get(pages));
    }

    /**
     * 招标人回复问题
     *
     * @param problem
     * @return {@link jnpf.base.ActionResult}
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/problem/replyProblem")
    public Message replyProblem(@RequestBody ProblemDTO problem) {
        Problem problemParent = problemService.getById(problem.getId());
        if (problemParent == null){
            return MsgUtil.fail("供应商提出的问题不存在,请重新刷新列表");
        }
        if (ProblemStatusEnum.ISSUED.getCode() != problemParent.getStatus()){
            return MsgUtil.fail("只有待回复的状态下的问题才能回复");
        }
        //设置必要字段 提出人id 供应商id等
        //problem.setRequiredFields(2);
        problem.setParentId(problem.getId());
        problem.setId(null);
        problem.setType(2);
        problem.buildBaseData(1);
        boolean save = problemService.save(problem);
        //如果保存成功需要更新供应商提出问题的状态
        if (save){
            problemParent.setStatus(ProblemStatusEnum.TO_BE_CONFIRMED.getCode());
            problemService.updateById(problemParent);
        }
        return MsgUtil.success();
    }

    /**
     * 投标人回执问题
     *
     * @param problem
     * @return {@link jnpf.base.ActionResult}
     */
    @PostMapping("/problem/receiptProblem")
    @Transactional(rollbackFor = Exception.class)
    public Message receiptProblem(@RequestBody ProblemDTO problem) {
        Problem problemParent = problemService.getById(problem.getId());
        if (problemParent == null){
            return MsgUtil.fail("供应商提出的问题不存在,请重新刷新列表");
        }
        if (ProblemStatusEnum.TO_BE_CONFIRMED.getCode() != problemParent.getStatus()){
            return MsgUtil.fail("只有待确认的状态下的问题才能回执");
        }
        //设置必要字段 提出人id 供应商id等
        //problem.setRequiredFields(3);
        problem.setParentId(problem.getId());
        problem.setId(null);
        problem.setType(3);
        problem.buildBaseData(1);
        boolean save = problemService.save(problem);
        //如果保存成功需要更新供应商提出问题的状态
        if (save){
            problemParent.setStatus(ProblemStatusEnum.CONFIRMED.getCode());
            problemService.updateById(problemParent);
        }
        return MsgUtil.success();
    }

    /**
     * 查看问题
     *
     * @param id
     * @return {@link jnpf.base.ActionResult}
     */
    @GetMapping("/problem/findProblem")
    public Message<JSONObject> findProblem(@RequestParam Long id) {
        //问题信息
        Problem problem = problemService.findProblem(id,1);
        //答疑信息
        Problem replyProblem = problemService.findProblem(id,2);
        //回执信息
        Problem receiptProblem = problemService.findProblem(id,3);
        JSONObject jsonObject = JSONUtil.createObj();
        jsonObject.putOpt("problem", problem);
        jsonObject.putOpt("replyProblem", replyProblem);
        jsonObject.putOpt("receiptProblem", receiptProblem);
        return MsgUtil.success(jsonObject);
    }

    /**
     *
     * @Description: 查看问题
     * @Author: zhongdl
     * @Date:2022/2/19 17:55
     * @param id:
     * @return: {@link Message< Problem> }
     **/
    @GetMapping("/problem/getProblemById")
    public  Message<Problem> getProblem(@RequestParam Long id){
        Problem problem = problemService.getById(id);
        return MsgUtil.success(problem);

    }
}
